# -*- coding: utf-8 -*-
# this file is released under public domain and you can use without limitations

d = db.catalog_folder
t = db.tag
f = db.catalog_file

### whereever you are, if you login ...
if session._next and auth.user and not request.function=='user':
    session_next,session._next=session._next,None
    redirect(session_next)
elif session._next:
    auth.settings.login_next=session._next
elif request.vars._next:
    session._next=request.vars._next
### ... go back there!

def index():
    rows = db(f).select(f.id.count(),f.size.sum(),cache=(cache.ram,3600)).first()
    info = (rows(f.id.count()),bytes(rows(f.size.sum())))
    response.menu = [
        (T('Browse (%s files, %s)',info), False, URL('root')),
        (T('Search'), False, URL('search')),
#        (T('Code'), False, URL('plugin_wiki','page',args='code')),
        (T('About'), False, URL('plugin_wiki','page',args='about')),
    ]
    if settings.community=='qcd':
        response.menu.insert(2,(T('Movies'), False, URL('movies')))

    return locals()

# @cache(request.env.path_info,60)
def root():
    path = '/'.join(request.args)
    if not path:
        page = db(d.root_id==0).select().first()
    else:
        page = db(d.path==path).select().first()
    if not page: redirect(URL('error'))
    tags = db(t.root_id==page.id).select()
    subfolders = db(d.root_id==page.id).select()
    patterns = db(f.root_id==page.id).select(f.pattern,f.id.count(),f.size.sum(),
                                             f.mtime.year(), groupby=f.pattern,orderby=f.pattern)
    return locals()

## fix this
@auth.requires_membership('editor')
def edit():    
    record = d(request.args(0)) or redirect(URL('root'))
    d.root_id.readable=d.root_id.writable=False
    d.path.writable=False
    def update_tags(form):
        db(t.root_id==record.id).delete()
        for tag in request.vars.tags.split(','):
            tag = tag.strip()
            if tag:
                t.insert(root_id=record.id,name=tag)
    form = crud.update(d,record,
                       onaccept=update_tags,
                       next=URL('root',args=record.path))
    tags = [tag.name for tag in db(t.root_id==record.id).select()]
    form.element('table').insert(-2,TR(LABEL('Tags:'),INPUT(_name='tags',value=', '.join(tags)),''))
    return locals()

# @cache(request.env.path_info,60)
def files():
    import os    
    path = '/'.join(request.args[:-1])    
    pattern = request.args[-1]
    page = db(d.path==path).select().first() or redirect(URL('root'))
    files = db(f.root_id==page.id)(f.pattern==pattern).select()
    if auth.user:        
        args = [auth.user.token_uuid] + request.args
        url='http://%s%s' % (request.env.http_host,URL('api','files.json',args=args))
        links = [r.link.replace('{{=url}}',url) for r in \
                     db(db.service.owner==auth.user.id).select()]
    return locals()

@auth.requires_login()
def services():
    if request.env.request_method:
        links = request.vars.links or []
        if not isinstance(links,list): links = [links]
        db(db.service.owner==auth.user.id).delete()
        for link in links:
            if link: db.service.insert(owner=auth.user.id,link=link)
    links = [r.link for r  in db(db.service.owner==auth.user.id).select()]
    form = SQLFORM.factory(Field('links','list:string',default=links),
                           formstyle = 'table2cols')
    return dict(form=form)

def search():
    tags = db().select(t.name,orderby=t.name,distinct=True)
    return locals()

def search2():
    prefix=request.vars.prefix
    prefixx = prefix+'/'
    n=len(prefixx)
    tags = db(t.name[:n]==prefixx).select(t.name,t.id.count(),groupby=t.name,orderby=t.name)
    data = [(r.tag.name[n:],r(t.id.count())) for r in tags]
    return locals()

def bytag():
    tag = request.vars.tag
    subquery = db(t.name==tag)._select(t.root_id)
    subfolders = db(d.id.belongs(subquery)).select()
    return locals()

def movies():
    if not settings.community=='qcd': raise HTTP(404)
    import glob, os, re
    movies = sorted(glob.glob(os.path.join(request.folder,'static','movies/*.mp4')))
    n = len(os.path.join(request.folder,'static'))+1
    v=len('.mdp.topological_charge_20.mp4')
    regex = re.compile('\.\d+$')
    links = [(m[n:-4]+'.thumb.jpeg',m[n:],
              URL('files',args=regex.sub('.nnnnn',m[n:-v].replace('movies','configs')).split('-'))) for m in movies]
    return dict(links=links)

def error():
    return locals()

def about():
    return locals()

def scripts():
    return locals()

def user():
    return dict(form=auth())

def download():
    return response.download(request,db)

def call():
    return service()

def demo():
    return locals()

def check_access():
    # logged in users can download
    if auth.user:
        return 'true'
    # basic auth requests http://anonymous:token@... are also allowed
    elif request.env.http_token:
        if db.token(uuid=request.env.http_token):
            return 'true'
    elif request.env.http_authorization:
        import base64
        up = base64.b64decode(request.env.http_authorization[6:])
        if up.startswith('anonymous:'):
            token_uuid = up[10:]
            print token_uuid
            if db.token(uuid=token_uuid):
                return 'true'
    return 'false'
